package apobates.gui.formatter.tree;

import java.util.Optional;

/**
 * JavaFx GUI Json TreeView Bean
 * @since 20230312
 */
public record JsonNodeItem(String name, String value, JsonNodeValueType typeName) {
    // 键名
    //private final String name;
    // 键值
    //private final String value;
    // 值类型
    //private final JsonNodeValueType typeName;
    private final static String ARR_TYPE = "[...]";
    private final static String OBJ_TYPE = "{...}";
    private final static String ELE_TYPE = "[%d]";
    private final static String ROOT = JsonNodeValueType.ROOT.getSymbol();

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }


    public String getClearValue(){
        if(getType().equals(JsonNodeValueType.STRING)){
            return getValue().replace("\"", "");
        }
        return getValue();
    }
    public JsonNodeValueType getType(){
        return Optional.ofNullable(typeName).orElse(isFullKV()? getNodeValueType() : JsonNodeValueType.DEFULT);
    }
    public JsonNodeValueType getNodeValueType(){
        if(getValue().equals(ARR_TYPE)){
            return JsonNodeValueType.ARRAY;
        }
        if(getValue().equals(OBJ_TYPE)){
            return JsonNodeValueType.OBJECT;
        }
        return JsonNodeValueType.DEFULT;
    }
    public JsonNodeValueType getNodeNameType(){
        if(getName().equals(ROOT)){
            return JsonNodeValueType.ROOT;
        }
        return JsonNodeValueType.ELEMENT;
    }
    /**
     * 常规的节点
     * @param name
     * @param value
     * @return
     */
    public static JsonNodeItem of(String name, String value, JsonNodeValueType typeName){
        return new JsonNodeItem(name, value, typeName);
    }
    /**
     * 含有下级的父对象节点
     * @param name
     * @return
     */
    public static JsonNodeItem ofObject(String name){
        return new JsonNodeItem(name, OBJ_TYPE, JsonNodeValueType.OBJECT);
    }
    /**
     * 根节点
     * @return
     */
    public static JsonNodeItem ofRoot(){
        return new JsonNodeItem(ROOT, ".", JsonNodeValueType.NODE);
    }

    /**
     * 数组元素的父节点
     * @param index 节点下标
     * @return
     */
    public static JsonNodeItem ofArrayElement(int index){
        return new JsonNodeItem(String.format(ELE_TYPE, index), "", JsonNodeValueType.ELEMENT);
    }
    /**
     * 含有下级的父数组节点
     * @param name
     * @return
     */
    public static JsonNodeItem ofArray(String name){
        return new JsonNodeItem(name, ARR_TYPE, JsonNodeValueType.ARRAY);
    }
    private boolean isFullKV(){
        return !value.equals(".") && !value.isEmpty();
    }

    @Override
    public String toString() {
        if(isFullKV()){
            return name+": "+value;
        }
        return name;
    }
}
